//
//  WCDBManager.swift
//  Casecord
//
//  Created by baozi on 2024/1/2.
//

import Foundation
import WCDBSwift

class WCDBManager: NSObject {
    private static let path: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! + "WCDB/\(UserService.userId).db"
    static let shared = WCDBManager()
    
    private(set) var database: Database!
    
    private override init() {
        super.init()
    }
    
    // 创建数据库
    func createDatabase() {
        let db = Database(at: Self.path)
        self.database = db
    }
    
    // 创建表
    func createTable<T: TableDecodable>(table: String, type: T.Type) {
        try? self.database.create(table: table, of: type)
    }
    
    // 插入某条数据
    func insertObject<T: TableEncodable>(into: String, object: T) {
        try? self.database.insert(object, intoTable: into)
    }
    
    // 插入某组数据
    func insertObjects<T: TableEncodable>(into: String, objects: [T]) {
        try? self.database.insert(objects, intoTable: into)
    }
    
    // 删除某张表中的某条数据
    func delete(from table: String, where condition: Condition?) {
        try? self.database.delete(fromTable: table, where: condition)
    }
    
    // 更新某条数据
    func update<T: TableEncodable>(which table: String, on properties: [PropertyConvertible], with object: T, where condition: Condition?) {
        try? self.database.update(table: table, on: properties, with: object, where: condition)
    }
    
    // 查询一组数据
    func queryObjecs<T: TableDecodable>(from table: String, type: T.Type, where condition: Condition? = nil, orderBy: [OrderBy]? = nil) -> [T]? {
        let objects: [T]? = try? self.database.getObjects(fromTable: table, where: condition, orderBy: orderBy)
        return objects
    }
    
    // 查询一条数据
    func queryObject<T: TableDecodable>(from table: String, type: T, where condition: Condition? = nil, orderBy: [OrderBy]? = nil) -> T? {
        let object: T? = try? self.database.getObject(fromTable: table, where: condition, orderBy: orderBy)
        return object
        
    }
    
}
